package com.listen.service.DB;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.listen.common.HttpClientProxy;
import com.listen.model.User;
import com.listen.vo.ClassParmsVO;

public class FuzhouServiceImpl {
	private static final Logger log = LoggerFactory.getLogger(FuzhouServiceImpl.class);
	private HttpClientProxy instance = new HttpClientProxy();
	private ConcurrentHashMap<String, Object>  resultMap = null;
	private CloseableHttpResponse response = null;
	private CloseableHttpClient httpClient = null;
	private String proxyInfo = null;
	
	public static void main(String[] args) {
		FuzhouServiceImpl fuzhou = new FuzhouServiceImpl();
		User user = new User();
		//362522199106154025,362522198311095023
		user.setCode("362522198311095023");
		user.setPassword("000000");
		fuzhou.lisetn(user, null);
	}
	
	//听课业务
	public Map<String,Object> lisetn(User user,String ip){
		ClassParmsVO vo = new ClassParmsVO();
		resultMap = new ConcurrentHashMap<>();
		resultMap.put("successFlag", "0");
		resultMap.put("dayNum", "0");
		resultMap.put("addNum", "0");
		toLoginPage(vo,user);
		return resultMap;
	}
	
	//根据url跳转到具体专业登录页面，并从页面抓取登录所需相关参数
	private void toLoginPage(ClassParmsVO vo,User user){
		String httpUrl = user.getAddress() == null ? "https://fzsjzy.cn/index" : user.getAddress();
		if("".equals(httpUrl)){
			print("抚州三类培训登录页面url为空");
		}else{
			try {
				response = instance.sendHttpGet(httpClient,httpUrl, proxyInfo);
				int state = response.getStatusLine().getStatusCode();
				if(state == 200){
					HttpEntity entity = response.getEntity();  
					String html = EntityUtils.toString(entity);
					System.out.println(html);
				    Document document = Jsoup.parse(html);
				    Element parm2 = document.getElementById("__EVENTVALIDATION");
				    vo.set__eventvalidation(parm2.attr("value"));
				    Element parm3 = document.getElementById("__VIEWSTATE");
				    vo.set__viewstate(parm3.attr("value"));
				    //login(vo,user);
				}else{
					print(user.getZyName()+"-"+user.getCode()+"-解析页面参数失败");
				}
			} catch (Exception e) {
				printError(user.getZyName()+"-"+user.getCode()+"-解析页面参数异常",e);
			} finally{
				instance.closeResource(response,httpClient);
			}
		}
	}
	
	private void print(String msg){
		resultMap.put("msg", msg);
		log.info(msg);
	}
	
	private void printError(String msg,Exception e){
		msg = msg + e.getMessage();
		resultMap.put("msg", msg);
		log.info(msg,e);
	}
}
